package com.retry.task.extension.processor;

import com.retry.task.extension.IExtension;
import com.retry.task.extension.annotation.ExtensionAnnotation;
import com.retry.task.extension.model.ExtensionSence;
import com.retry.task.extension.repository.IExtensionRepository;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * spring 项目启动过程中加载扩展点实现类
 */
public class ExtensionProcessor implements BeanPostProcessor {


    private static final Logger LOGGER = LoggerFactory.getLogger(ExtensionProcessor.class);
    @Autowired
    private IExtensionRepository iExtensionRepository;


    /**
     * bean对象初始化之前进行加载
     *
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        doRegister(bean);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    private void doRegister(Object bean) {
        //如果没有实现IExtension扩展类，则不能注册
        if (!(bean instanceof IExtension)) {
            return;
        }
        ExtensionAnnotation extensionAnnotation = bean.getClass().getAnnotation(ExtensionAnnotation.class);
        Class<?>[] extensionClassArr = extensionAnnotation.extensionClass();
        for (Class<?> clazz : extensionClassArr) {
            if (!IExtension.class.isAssignableFrom(clazz)) {
                LOGGER.warn("[ExtensionProcessor-doRegister] class {} is not children of IExtension", clazz.getName());
                continue;
            }
            ExtensionSence extensionSence = ExtensionSence.valueOf(extensionAnnotation.scene(), extensionAnnotation.useCase());
            extensionSence.setClazz(clazz);
            iExtensionRepository.loadExtension((IExtension) bean, extensionSence);
        }
    }
}
